package limeirafol.gui;

import java.awt.Component;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import limeirafol.Global;
import limeirafol.remote.ParametroVO;
import lbframework.bean.checkBox.LBCheckBox;
import lbframework.classe.Util;
import lbframework.classe.LBException;
import lbframework.bean.comboBox.LBComboBox;
import lbframework.bean.consultaCampo.LBConsultaCampo;
import lbframework.bean.fileChooser.LBFileChooser;
import lbframework.bean.internalFrame.LBInternalFrame;
import lbframework.bean.mdiFrame.LBMdiFrame;
import lbframework.bean.table.LBColumnTable;
import lbframework.bean.textField.LBTextField;
import limeirafol.bean.BeanAdministacao;

public class ParametroGUI extends LBInternalFrame {

    private Vector<ParametroVO> vParametro = null;
    private boolean achou = false;
    private BeanAdministacao beanAdministracao = new BeanAdministacao();
    private boolean cotacao = false;

    public ParametroGUI(LBMdiFrame i_mdiFrame) throws Exception {
        super(i_mdiFrame);
        initComponents();

        centralizarForm();
    }

    public void setCotacao(boolean i_cotacao) throws Exception {
        cotacao = i_cotacao;
    }

    public void carregarParametro(int... i_parametro) throws Exception {
        vParametro = new Vector();

        LBColumnTable[] colunas = new LBColumnTable[]{
            new LBColumnTable("Parâmetro", 190, true, SwingConstants.LEFT, false, null),
            new LBColumnTable("Valor", 364, true, SwingConstants.LEFT, true, null)
        };

        Object[][] dados = new Object[i_parametro.length][colunas.length];

        Object oCampo = null;

        int i = 0;

        for (int idParametro : i_parametro) {
            ParametroVO oParametro = Global.getParametro(idParametro);

            if (idParametro == 5) {
                achou = true;
            }

            switch (idParametro) {

                case 2:
                case 3:
                case 4:
                    //numero
                    LBTextField txtNumero = new LBTextField();
                    txtNumero.setMascara(LBTextField.MASK_NUMERO);
                    txtNumero.setInt(oParametro.getInt());

                    oCampo = txtNumero;
                    break;

                case 5:
                    //decimal 2
                    LBTextField txtDecimal2 = new LBTextField();
                    txtDecimal2.setMascara(LBTextField.MASK_DECIMAL2);
                    txtDecimal2.setDouble(oParametro.getDouble());

                    oCampo = txtDecimal2;
                    break;

                case 171:
                    //texto
                    LBTextField txtTexto = new LBTextField();
                    txtTexto.setMascara(LBTextField.MASK_TEXTO);
                    txtTexto.setText(oParametro.getString());
                    oCampo = txtTexto;
                    break;

                case 1:
                    //check box
                    LBCheckBox chkCampo = new LBCheckBox();
                    chkCampo.setSelected(oParametro.getBoolean());

                    oCampo = chkCampo;
                    break;

                case 197:
                    //diretorio
                    LBFileChooser flcDiretorio = new LBFileChooser();
                    flcDiretorio.setFileSelectionMode(LBFileChooser.DIRECTORIES_ONLY);
                    flcDiretorio.setDialogType(LBFileChooser.OPEN_DIALOG);
                    flcDiretorio.setArquivo(oParametro.getString());

                    oCampo = flcDiretorio;
                    break;

                default:
                    throw new LBException("Parâmetro " + idParametro + " não configurado!");
            }

            dados[i][0] = oParametro.descricao;
            dados[i][1] = oCampo;

            vParametro.add(oParametro);

            i++;
        }

        tblParametro.setModel(dados, colunas);
        tblParametro.setRowHeight(22);

        TableColumn column = tblParametro.getColumnModel().getColumn(1);
        column.setCellEditor(new MyDefaultCellEditor());
        column.setCellRenderer(new MyTableCellRenderer());
    }

    @Override
    public void salvar() throws Exception {
        for (int i = 0; i < tblParametro.getRowCount(); i++) {
            ParametroVO oParametro = vParametro.get(i);

            Object oCampo = tblParametro.getValueAt(i, 1);

            if (oCampo instanceof LBTextField) {
                LBTextField txtCampo = (LBTextField) oCampo;
                oParametro.valor = txtCampo.getText();

            } else if (oCampo instanceof LBCheckBox) {
                LBCheckBox chkCampo = (LBCheckBox) oCampo;
                oParametro.valor = String.valueOf(chkCampo.isSelected());

            } else if (oCampo instanceof LBComboBox) {
                LBComboBox cboCampo = (LBComboBox) oCampo;
                oParametro.valor = String.valueOf(cboCampo.getId());

            } else if (oCampo instanceof LBFileChooser) {
                LBFileChooser flcArquivo = (LBFileChooser) oCampo;
                oParametro.valor = flcArquivo.getArquivo();

            } else if (oCampo instanceof LBConsultaCampo) {
                LBConsultaCampo cnsCampo = (LBConsultaCampo) oCampo;
                oParametro.valor = String.valueOf(cnsCampo.getId());

            } else {
                throw new LBException("Objeto não configurado!");
            }
        }

        Global.salvarParametro(vParametro);

        if (achou) {
            beanAdministracao.administrarCustoBanho();
        }

        Util.exibirMensagem(Util.MSG_SALVO_SUCESSO, getTitle());

        if (cotacao) {
            sair();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblParametro = new lbframework.bean.table.LBTable();
        vRPanel1 = new lbframework.bean.panel.LBPanel();
        btnSair = new lbframework.bean.button.LBButton();
        btnSalvar = new lbframework.bean.button.LBButton();
        vRToolBarPadrao1 = new lbframework.bean.toolBarPadrao.LBToolBarPadrao(this);

        setTitle("Parâmetros");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                formComponentHidden(evt);
            }
        });

        tblParametro.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblParametro.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblParametroMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tblParametroMouseReleased(evt);
            }
        });
        tblParametro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblParametroKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tblParametroKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tblParametro);

        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/sair.png"))); // NOI18N
        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lbframework/img/salvar.png"))); // NOI18N
        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout vRPanel1Layout = new javax.swing.GroupLayout(vRPanel1);
        vRPanel1.setLayout(vRPanel1Layout);
        vRPanel1Layout.setHorizontalGroup(
            vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, vRPanel1Layout.createSequentialGroup()
                .addContainerGap(414, Short.MAX_VALUE)
                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        vRPanel1Layout.setVerticalGroup(
            vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(vRPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        vRToolBarPadrao1.setRollover(true);
        vRToolBarPadrao1.setVisibleSalvar(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE)
                    .addComponent(vRToolBarPadrao1, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE)
                    .addComponent(vRPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(vRToolBarPadrao1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(vRPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        try {
            sair();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_btnSairActionPerformed

    private void formComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentHidden
    }//GEN-LAST:event_formComponentHidden

    private void tblParametroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblParametroKeyPressed
    }//GEN-LAST:event_tblParametroKeyPressed

    private void tblParametroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblParametroMouseClicked
    }//GEN-LAST:event_tblParametroMouseClicked

    private void tblParametroMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblParametroMouseReleased
    }//GEN-LAST:event_tblParametroMouseReleased

    private void tblParametroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblParametroKeyReleased
    }//GEN-LAST:event_tblParametroKeyReleased

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        try {
            salvar();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, getTitle());
        }
    }//GEN-LAST:event_btnSalvarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private lbframework.bean.button.LBButton btnSair;
    private lbframework.bean.button.LBButton btnSalvar;
    private javax.swing.JScrollPane jScrollPane1;
    private lbframework.bean.table.LBTable tblParametro;
    private lbframework.bean.panel.LBPanel vRPanel1;
    private lbframework.bean.toolBarPadrao.LBToolBarPadrao vRToolBarPadrao1;
    // End of variables declaration                   

    void setCentralizarForm() throws Exception {
        this.centralizarForm();
    }
    // End of variables declaration//GEN-END:variables

    private class MyDefaultCellEditor extends DefaultCellEditor {

        private Object obj = null;

        public MyDefaultCellEditor() {
            super(new LBComboBox());
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            if (value == null) {
                return null;
            }

            obj = value;
            return (Component) value;
        }

        @Override
        public Object getCellEditorValue() {
            return obj;
        }
    }

    private class MyTableCellRenderer extends LBComboBox implements TableCellRenderer {

        public MyTableCellRenderer() {
            super();
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            if (column == 0) {
                return new JLabel(value == null ? "" : value.toString());
            }

            return (Component) value;
        }
    }
}
